package com.rms.recruit_management_system.controller;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rms.recruit_management_system.pojo.Interview;
import com.rms.recruit_management_system.pojo.Resume;
import com.rms.recruit_management_system.pojo.User;
import com.rms.recruit_management_system.service.UserService;
import com.rms.recruit_management_system.service.impl.UserServiceImpl;
import com.rms.recruit_management_system.utils.JwtUtil;
import com.rms.recruit_management_system.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
public class UserController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping("/user/login")
    public Result<?> userLogin(@RequestBody User user){
        User users=userService.userLogin(user);
        if(users!=null){
            HashMap<String,Object> userMap=new HashMap<>();
            userMap.put("userId",users.getUserId());
            userMap.put("username",users.getUsername());
            userMap.put("userPic",users.getUserPic());
            String token= JwtUtil.generateToken(users.getUsername(),users.getUserId());
            HashMap<String,Object> map=new HashMap<>();
            map.put("token",token);
            map.put("user",userMap);
            users.setUpdateTime(LocalDateTime.now());
            userService.updateUser(users);
            return new Result<>(200,"登录成功",map);
        }

        return new Result<>(400,"登录失败");
    }

    @RequestMapping("/user/register")
    public Result<?> userRegister(@RequestBody User user){
        userService.userRegister(user);
        return new Result<>(200,"注册成功");
    }
    @RequestMapping("/user/delete/{userId}")
    public Result<?> deleteUser(@PathVariable Integer userId){
        userService.deleteUser(userId);
        cleanCache("user_*");
        return new Result<>(200,"SUCCESS");
    }
    @RequestMapping("/user/getUserPage")
    public Result<?> getUserPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                 @RequestParam("") String search){
        String key= "user_:"+pageNum+"_"+pageSize+"_"+search;
        IPage<User> page=(IPage<User>) redisTemplate.opsForValue().get(key);
        if(page!=null && page.getTotal()>0){
            return new Result<>(200,"SUCCESS",page);
        }
         page=userService.getUserPage(pageNum,pageSize,search);
        redisTemplate.opsForValue().set(key,page,60, TimeUnit.SECONDS);
        return new Result<>(200,"SUCCESS",page);
    }

    @RequestMapping("/user/getUserInfo/{userId}")
    public Result<?> getUserInfo(@PathVariable Integer userId){
        User user=userService.getUserById(userId);
        return new Result<>(200,"SUCCESS",user);
    }
    @RequestMapping("/user/updateUser")
    public Result<?> updateUser(@RequestBody User user){
        userService.updateUser(user);
        return new Result<>(200,"SUCCESS");
    }

    @RequestMapping("/user/getResumeByUserId/{userId}")
    public Result<?> getResumeByUserId(@PathVariable Integer userId){
        List<Resume> resume=userService.getResumeByUserId(userId);
        return new Result<>(200,"SUCCESS",resume);
    }
    @RequestMapping("/user/getInterviewByUserId/{userId}")
    public Result<?> getInterviewByUserId(@PathVariable Integer userId){
        List<Interview> interview=userService.getInterviewByUserId(userId);
        return new Result<>(200,"SUCCESS",interview);
    }

    @PostMapping("/user/sendEmailCode")
    public Result<?> findPassword(@RequestParam String email){
        userService.findPassword(email);
        return new Result<>(200,"SUCCESS");
    }
    @PostMapping("/user/checkCode")
    public Result<?> checkCode(@RequestParam String email,@RequestParam String code,@RequestParam String password){
        String key="code_"+email;
        String codeRedis=(String) redisTemplate.opsForValue().get(key);
        if(codeRedis.equals(code)){
            User user=new User();
            user.setPassword(MD5.create().digestHex(password));
            userService.update(user,new UpdateWrapper<User>().eq("email",email));
            return new Result<>(200,"SUCCESS");
        }
        return new Result<>(400,"验证码错误");
    }

    @PostMapping("/user/loginByEmail")
    public Result<?> loginByEmail(@RequestParam String email,@RequestParam String code){
        User user=userService.getUserByEmail(email);
        if(user!=null){
            String key="code_"+email;
            String codeRedis=(String) redisTemplate.opsForValue().get(key);
            if(codeRedis.equals(code)){
                HashMap<String,Object> userMap=new HashMap<>();
                userMap.put("userId",user.getUserId());
                userMap.put("username",user.getUsername());
                userMap.put("userPic",user.getUserPic());
                String token= JwtUtil.generateToken(user.getUsername(),user.getUserId());
                HashMap<String,Object> map=new HashMap<>();
                map.put("token",token);
                map.put("user",userMap);
                user.setUpdateTime(LocalDateTime.now());
                userService.updateUser(user);
                return new Result<>(200,"SUCCESS",map);
            }
        }
        return new Result<>(400,"验证码错误");

    }
    public void cleanCache(String pattern){
        Set keys=redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
